#!/usr/bin/env python3
"""
演示数据生成脚本
用于生成更多的演示数据
"""

import json
import random
from datetime import datetime, timedelta

def generate_order_id(prefix="WO", year="2024", start_num=1):
    """生成工单编号"""
    return f"{prefix}-{year}-{start_num:03d}"

def generate_progress_data(count=20):
    """生成进度数据"""
    data = []
    factories = ['factory1', 'factory2', 'factory3']
    workshops = ['workshop1', 'workshop2', 'workshop3']
    lines = ['line1', 'line2', 'line3']
    statuses = ['running', 'completed', 'paused']
    
    for i in range(count):
        order_id = generate_order_id(start_num=i+1)
        factory = random.choice(factories)
        workshop = random.choice(workshops)
        line = random.choice(lines)
        status = random.choice(statuses)
        
        input_qty = random.randint(500, 2000)
        
        if status == 'completed':
            completed_qty = input_qty
            yield_rate = round(random.uniform(97.0, 99.5), 1)
        elif status == 'running':
            completed_qty = random.randint(100, input_qty - 100)
            yield_rate = round(random.uniform(97.0, 99.5), 1)
        else:  # paused
            completed_qty = 0
            yield_rate = 0
        
        defect_qty = int(completed_qty * (100 - yield_rate) / 100) if completed_qty > 0 else 0
        scrap_qty = random.randint(0, max(1, defect_qty // 3))
        rework_qty = defect_qty - scrap_qty
        
        item = {
            "orderId": order_id,
            "factory": factory,
            "workshop": workshop,
            "line": line,
            "inputQty": input_qty,
            "completedQty": completed_qty,
            "yield": yield_rate,
            "defectQty": defect_qty,
            "orderCompletedQty": completed_qty,
            "scrapQty": scrap_qty,
            "reworkQty": rework_qty,
            "status": status,
            "startTime": (datetime.now() - timedelta(days=random.randint(1, 30))).strftime('%Y-%m-%d %H:%M:%S')
        }
        
        if status == 'completed':
            item['endTime'] = (datetime.now() - timedelta(hours=random.randint(1, 24))).strftime('%Y-%m-%d %H:%M:%S')
        elif status == 'running':
            item['estimatedEndTime'] = (datetime.now() + timedelta(hours=random.randint(1, 48))).strftime('%Y-%m-%d %H:%M:%S')
        elif status == 'paused':
            item['pauseTime'] = (datetime.now() - timedelta(hours=random.randint(1, 12))).strftime('%Y-%m-%d %H:%M:%S')
        
        data.append(item)
    
    return data

def generate_quality_data(progress_data):
    """生成品质数据"""
    data = []
    
    for progress in progress_data:
        if progress['status'] == 'paused':
            # 暂停的工单没有品质数据
            quality_item = {
                "orderId": progress['orderId'],
                "strippingYield": 0,
                "interferenceYield": 0,
                "endInspectionYield": 0,
                "insertionLossYield": 0,
                "polarityYield": 0,
                "overallYield": 0,
                "lastUpdate": progress.get('pauseTime', datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
            }
        else:
            # 生成各工序良率
            stripping_yield = round(random.uniform(98.0, 99.9), 1)
            interference_yield = round(random.uniform(97.5, 99.8), 1)
            end_inspection_yield = round(random.uniform(98.5, 99.9), 1)
            insertion_loss_yield = round(random.uniform(97.0, 99.5), 1)
            polarity_yield = round(random.uniform(98.0, 99.7), 1)
            
            # 计算综合良率
            overall_yield = round((stripping_yield + interference_yield + 
                                 end_inspection_yield + insertion_loss_yield + 
                                 polarity_yield) / 5, 1)
            
            quality_item = {
                "orderId": progress['orderId'],
                "strippingYield": stripping_yield,
                "interferenceYield": interference_yield,
                "endInspectionYield": end_inspection_yield,
                "insertionLossYield": insertion_loss_yield,
                "polarityYield": polarity_yield,
                "overallYield": overall_yield,
                "lastUpdate": datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            }
        
        data.append(quality_item)
    
    return data

def generate_management_data():
    """生成人机料法环数据"""
    processes = ['剥纤', '干涉', '端检', '插回损', '极性']
    personnel = ['张三', '李四', '王五', '赵六', '钱七', '孙八', '周九', '吴十']
    equipment_prefixes = ['剥纤机', '干涉仪', '端检仪', '插回损测试仪', '极性测试仪']
    
    data = []
    
    for i, process in enumerate(processes):
        equipment = f"{equipment_prefixes[i]}-{chr(65+i)}{i+1:02d}"
        personnel_name = personnel[i % len(personnel)]
        
        item = {
            "process": process,
            "personnel": personnel_name,
            "equipment": equipment,
            "drawing": "已上传",
            "sop": "已上传",
            "temperature": f"{random.randint(20, 25)}°C",
            "humidity": f"{random.randint(40, 50)}%",
            "status": "正常",
            "lastMaintenance": (datetime.now() - timedelta(days=random.randint(5, 15))).strftime('%Y-%m-%d'),
            "nextMaintenance": (datetime.now() + timedelta(days=random.randint(5, 15))).strftime('%Y-%m-%d')
        }
        
        data.append(item)
    
    return data

def main():
    """主函数"""
    print("生成演示数据...")
    
    # 生成进度数据
    progress_data = generate_progress_data(20)
    print(f"生成了 {len(progress_data)} 条进度数据")
    
    # 生成品质数据
    quality_data = generate_quality_data(progress_data)
    print(f"生成了 {len(quality_data)} 条品质数据")
    
    # 生成管理数据
    management_data = generate_management_data()
    print(f"生成了 {len(management_data)} 条管理数据")
    
    # 保存到文件
    demo_data = {
        "progress": progress_data,
        "quality": quality_data,
        "management": management_data,
        "generated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    }
    
    with open('demo_data.json', 'w', encoding='utf-8') as f:
        json.dump(demo_data, f, ensure_ascii=False, indent=2)
    
    print("演示数据已保存到 demo_data.json")
    
    # 显示统计信息
    print("\n数据统计:")
    print(f"总工单数: {len(progress_data)}")
    print(f"生产中: {len([p for p in progress_data if p['status'] == 'running'])}")
    print(f"已完成: {len([p for p in progress_data if p['status'] == 'completed'])}")
    print(f"暂停中: {len([p for p in progress_data if p['status'] == 'paused'])}")
    
    # 计算平均良率
    active_orders = [p for p in progress_data if p['status'] == 'running']
    if active_orders:
        avg_yield = sum(p['yield'] for p in active_orders) / len(active_orders)
        print(f"平均良率: {avg_yield:.1f}%")

if __name__ == "__main__":
    main()
